package com.learn.thread;

/**
 * 线程通信实例，使用两个线程打印1-100，线程1，线程2交替打印
 *
 * 涉及三个方法：
 * wait()、notify、notifyAll
 */
class PrintNumber implements Runnable{
    private int number = 1;

    @Override
    public void run() {
        while (true){
            synchronized (this) {
                notify();
                if(number < 100){
                    System.out.println(Thread.currentThread().getName() + ":" + number);
                    number++;
                    try {
                        wait();//使调用该方法的线程进入阻塞态
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }else
                    break;
            }
        }
    }
}

public class CommunicationThread {

    public static void main(String[] args) {
        PrintNumber number = new PrintNumber();
        Thread t1 = new Thread(number);
        Thread t2 = new Thread(number);

        t1.setName("线程1");
        t2.setName("线程2");
        t1.start();
        t2.start();
    }

}
